#include "DownloadFile.h"
/***
 * @Author: 玄绮 shijiahansi@qq.com
 * @Date: 2024-06-10 21:17:47
 * @LastEditors: 玄绮 shijiahansi@qq.com
 * @LastEditTime: 2024-06-10 21:17:47
 * @FilePath: \client\src\tools\http\DownloadFIle.cpp
 * @Description:
 * @
 * @Copyright (c) 2024 by 玄绮, All Rights Reserved.
 */
#include <QJsonObject>
#include <QJsonValue>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <cstddef>
#include <memory>
#include <qfileinfo.h>
#include <qjsondocument.h>
#include <qnetworkreply.h>
#include <qnetworkrequest.h>

QNetworkAccessManager DownloadFile::manager;

DownloadFile::DownloadFile(QObject *parent) : QObject(parent) {}

DownloadFile::~DownloadFile() {}

void DownloadFile::download(QString url) {
  if (!url.startsWith("http")) {
    url.push_front("http://");
  }

  QNetworkRequest request;

  // 发送https请求前准备工作;

  if (url.startsWith("https://")) {
    QSslConfiguration conf = request.sslConfiguration();
    conf.setPeerVerifyMode(QSslSocket::VerifyNone);
    conf.setProtocol(QSsl::TlsV1SslV3);
    request.setSslConfiguration(conf);
  }
  request.setUrl(url);
  auto reply = manager.get(request);
  auto data = std::make_shared<QByteArray>();

  // 请求完成
  connect(reply, &QNetworkReply::finished, this, &DownloadFile::on_finished);

  // 可以读数据
  connect(reply, &QNetworkReply::readyRead, [=]() {
    size_t contentLenght =
        reply->header(QNetworkRequest::ContentLengthHeader).toUInt();
    data->push_back(reply->readAll());
    if (data->size() >= contentLenght) {
      emit finished(data);
      reply->deleteLater();
    }
  });

  connect(reply,
          QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error),
          [=](QNetworkReply::NetworkError code) {
            QNetworkReply *reply = static_cast<QNetworkReply *>(sender());

            /*这里可以通过 code 知道哪里错了*/
            // std::cout << "error:" <<
            qDebug() << "error: " << code;
            reply->deleteLater();
          });
}

void DownloadFile::on_finished() {
  QNetworkReply *reply = static_cast<QNetworkReply *>(sender());

  size_t contentLenght =
      reply->header(QNetworkRequest::ContentLengthHeader).toUInt();
  if (contentLenght == 0) {
    reply->deleteLater();
  }
}
